"""
自定义分页组件，以后使用过程中，需要：
在视图函数中：
    def pretty_list(request):

        # 1.根据自己的情况去筛选自己的数据
        queryset = models.PrettyNum.objects.all()

        # 2.实例化分页对象
        page_object = Pagination(request, queryset)

        context = {
            "queryset": page_object.page_queryset,  # 分完页数据
            "page_string": page_object.html(),      # 页码
        }
        return render(request, "pretty_list.html", context)

在html中：
        # 1.数据
        {% for obj in queryset %}
            {{ obj.xx }}
        {% endfor %}

        # 2.分页
        <ul class="pagination">
            {{ page_string }}
        </ul>

"""
from django.utils.safestring import mark_safe
import copy


class Pagination(object):

    def __init__(self, request, queryset, page_param="page", page_size=10, plus=5):
        """
        :param request: 请求对象
        :param queryset: 查询符合条件的数据，根据这个数据分页处理
        :param page_param: 每页显示数据条数
        :param page_size: 在URL中传递的获取分页的参数，例如：/pretty/list/?page=23
        :param plus: 显示当前页的 前或后几页(页码)
        """

        # 分页时候，保留原来的搜索条件
        query_dict = copy.deepcopy(request.GET) #原request.GET中mutable=False，不允许.setlist更改拼接
        query_dict._mutable = True              #深拷贝这个方法，mutable=True，允许.setlist拼接
        self.query_dict = query_dict

        page = request.GET.get(page_param, "1")
        if page.isdecimal():
            page = int(page)
        else:
            page = 1

        self.page = page
        self.page_size = page_size
        self.page_param=page_param
        self.start = (page - 1) * page_size
        self.end = page * page_size
        self.page_queryset = queryset[self.start: self.end]
        self.total_count = queryset.count()
        total_page_count, div = divmod(self.total_count, page_size)
        if div:
            total_page_count += 1
        self.total_page_count = total_page_count
        self.plus = plus

    def html(self):
        if self.total_page_count <= 2 * self.plus + 1:
            # 数据页面少于10页
            start_page = 1
            end_page = self.total_page_count + 1
        else:
            # 数据库数据比较多
            if self.page <= self.plus:
                # 当前页小于5页，避免显示负数页面
                start_page = 1
                end_page = 2 * self.plus + 1 + 1
            elif self.page + self.plus >= self.total_page_count:
                start_page = self.total_page_count - 2 * self.plus
                end_page = self.total_page_count + 1
            else:
                start_page = self.page - self.plus
                end_page = self.page + self.plus + 1
            # 后台生成页码，展示到前端
        page_str_list = []

        # 首页
        self.query_dict.setlist(self.page_param,[1])
        first_page = '<li><a href="?{}">首页</a></li>'.format(self.query_dict.urlencode())
        page_str_list.append(first_page)

        # 上一页
        if self.page > 1:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            prev_page = '<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())
        else:
            self.query_dict.setlist(self.page_param, [1])
            prev_page = '<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())
        page_str_list.append(prev_page)

        # 页面
        for i in range(start_page, end_page):
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                ele = '<li class="active"><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            else:
                ele = '<li><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            page_str_list.append(ele)

        # 下一页
        if self.page < self.total_page_count:
            self.query_dict.setlist(self.page_param, [self.page + 1])
            next_page = '<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode())
        else:
            self.query_dict.setlist(self.page_param, [self.total_page_count])
            next_page = '<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode())
        page_str_list.append(next_page)

        # 尾页
        self.query_dict.setlist(self.page_param, [self.total_page_count])
        last_page = '<li><a href="?{}">尾页</a></li>'.format(self.query_dict.urlencode())
        page_str_list.append(last_page)

        # 跳转框
        go_page = """
           <li>
               <form method="get" style="float: left;margin-left: -1px" >
                   <div class="input-group" style="width:110px">
                       <input type="text" name="page" class="form-control" placeholder="页码" >
                           <span class="input-group-btn">
                               <button class="btn btn-default" type="submit">跳转</button>
                           </span>
                   </div>
               </form>
           </li>
           """
        page_str_list.append(go_page)

        page_string = mark_safe("".join(page_str_list))  # 标记内容为安全，前端显示为html显示
        return page_string
